package top.kaoshanji.v1ch12a.repositories;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import top.kaoshanji.v1ch12a.model.Purchase;

import java.util.List;

/**
 * @author kaoshanji
 * ^_^
 * create time 2025/5/1 17:21
 */
@Repository
public class PurchaseRepository {

    private final JdbcTemplate jdbcTemplate;

    public PurchaseRepository(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public void savePurchase(Purchase purchase) {
        String sql = " INSERT INTO purchase (product, price) VALUES (?, ?) ";
        jdbcTemplate.update(sql, purchase.getProduct(), purchase.getPrice());
    }

    public List<Purchase> queryPurchaseList() {
        String sql = " SELECT id, product, price FROM purchase ORDER BY id ";

        RowMapper<Purchase> purchaseRowMapper = (r, i) -> {
          Purchase purchase = new Purchase();
          purchase.setId(r.getInt("id"));
          purchase.setProduct(r.getString("product"));
          purchase.setPrice(r.getBigDecimal("price"));

          return purchase;
        };

        return jdbcTemplate.query(sql, purchaseRowMapper);
    }


}
